package com.woniuxy.meal.config;


import com.woniuxy.meal.exception.userException.UserException;
import com.woniuxy.meal.exception.userException.UserExceptionCode;
import com.woniuxy.meal.util.JwtUtil;
import com.woniuxy.meal.util.RedisUtil;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.ExpiredJwtException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;

@Component
public class MyInterceptor implements HandlerInterceptor {
    @Autowired
    private RedisUtil redisUtil;
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        System.out.println("前置处理");
        //取出请求头中的token
        String token = request.getHeader("token");
//        System.out.println(token);
        if (token==null||"".equals(token)){
            throw new UserException(UserExceptionCode.USER_NOT_LOGIN);
        }
        try {
            //尝试解析token
            JwtUtil.parseToken(token);
        }catch (ExpiredJwtException e){
            if (!redisUtil.exist(token)){
                throw e;
            }else {
                String refreshToken = redisUtil.getString(token);
                Claims claims = JwtUtil.parseToken(refreshToken);
                HashMap<String,Object> body = new HashMap<String,Object>();
                body.put("sub",claims.get("sub"));
                String newToken = JwtUtil.createToken(body, 30);
                String newRefreshToken = JwtUtil.createToken(body,8*60);
                redisUtil.setString(newToken,newRefreshToken,8*60*60);
                response.setHeader("token",newToken);

            }
        }


        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        System.out.println("响应后置处理");
        String token = request.getHeader("token");
        if(token!=null&&!("".equals(token))){
            try {
                JwtUtil.parseToken(token);
            }catch (ExpiredJwtException e){
                redisUtil.delete(token);
            }
        }
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        System.out.println("响应前处理");
    }
}
